package com.crealth.crmserver;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.mina.core.session.IoSession;

public final class SessionManager {
	private static SessionManager instance;	
    public static Map<Long, IoSession> clientSessions;  // Mina 自己的Session管理
    public static Set<IoSession> boradShowClientSessions =
    		new HashSet<IoSession>();
    //  保存每个用户的Session   key:userID
    public static Map<Integer, IoSession> userSessions = 
    		new ConcurrentHashMap<Integer, IoSession>();

    public static SessionManager getInstance() {
    	if (instance == null) {
    		instance = new SessionManager();
    	}
        return instance;
    }

    public static void setClientSessions(Map<Long, IoSession> userSessions) {
    	SessionManager.clientSessions = userSessions;
    }
    
    public static IoSession getSessionBySessionID(long sessionId) {
        return SessionManager.clientSessions.get(sessionId);
    }
    
    public static void addBoardClientSession(IoSession cliSession) {
    	boradShowClientSessions.add(cliSession);
    }
    //  删除不在线的
    public static void removeOutlineBoradSession() {
    	Iterator<IoSession> boradIt = boradShowClientSessions.iterator();
    	while (boradIt.hasNext()) {
    		IoSession curSession = boradIt.next();
    		if (!curSession.isConnected()) {
    			boradIt.remove();
    		}
    	}
    }
    
    //  退出时  清除
    public static void removeBoradSessionLogout(IoSession session) {
    	if (session == null) {
    		return;
    	}
    	Iterator<IoSession> boradIt = boradShowClientSessions.iterator();
    	while (boradIt.hasNext()) {
    		IoSession curSession = boradIt.next();
    		if (curSession.equals(session) || curSession == session) {
    			boradIt.remove();
    		}
    	}
    }
    
    public static void addUserSession(int userID, IoSession cliSession) {
    	if (userSessions.containsKey(userID)) {
    		userSessions.remove(userID);
    	}
    	userSessions.put(userID, cliSession);
    }
    
    public static IoSession getUserSessionByID(int userID) {
    	if (userSessions.containsKey(userID)) {
    		return userSessions.get(userID);
    	}
    	
    	return null;
    }
    
    public static void removeUserSessionByID(int userID) {
    	if (userSessions.containsKey(userID)) {
    		IoSession userSession = userSessions.get(userID);
    		removeBoradSessionLogout(userSession);
    		userSessions.remove(userID);
    	}
    }
    
}


